<template>
  <div v-if="moduleNameOptions&&activePageForm">
    <el-dialog
      :title="(mode==='add'?'新增':'编辑')+moduleNameOptions[activePageForm.modules[activePageForm.activeModuleIndex].type].label"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :append-to-body="true"
      width="850px"
      @close="close"
    >
      <el-form ref="form" v-loading="false" :model="form" :rules="rules" label-width="110px" size="small">
        <div
          v-for="(v, k) in moduleNameOptions[activePageForm.modules[activePageForm.activeModuleIndex].type].params"
          :key="k"
        >
          <el-form-item v-if="k == 'titleType'" :label="v.label || '标题类型'" prop="titleType">
            <el-select v-model="form.titleType" placeholder="请选择" class="w-400">
              <el-option label="文本标题" value="text" />
              <el-option label="图片标题" value="image" />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="
              (k == 'title' && !form.titleType) ||
                (k == 'title' && form.titleType === 'text')
            "
            :label="v.label || '标题'"
            prop="title"
          >
            <el-input v-model.trim="form.title" maxlength="4" show-word-limit class="w-400" />
          </el-form-item>

          <el-form-item v-if="k == 'subTitle'&&form.titleType=='text'" :label="v.label || '副标题'" prop="subTitle">
            <el-input v-model.trim="form.subTitle" maxlength="4" show-word-limit class="w-400" />
          </el-form-item>

          <!-- 图片类-->
          <el-form-item v-if="k == 'pic'" :label="v.label || '图片'" prop="pic">
            <div class="upload-container">
              <el-upload
                :action="imageUploadUrl"
                :show-file-list="false"
                :headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
                :before-upload="handleImgBefore"
                :on-success="
                  (res, file) => {
                    return handleImgSuccess(res, file, 'pic');
                  }
                "
                :style="{ width: v.width + 'px', height: v.height + 'px' }"
                class="app-uploader-img-plus"
              >
                <el-image
                  v-if="form.pic"
                  :style="{ width: v.width + 'px', height: v.height + 'px' }"
                  :src="fileBaseUrl + form.pic"
                  class="img"
                  fit="fill"
                />
                <i v-else :style="{ width: v.width + 'px', height: v.height + 'px' }" class="el-icon-plus" />
              </el-upload>
            </div>
            <div style="font-size: 12px">只能上传jpg/png/gif文件，建议像素{{ v.width+' * '+ v.height }}，且不超过1MB</div>
            <el-button
              v-if="form.pic"
              size="small"
              round
              type="text"
              class="app-text-color-danger"
              @click="form.pic=null"
            >删除{{ v.label|| '图片' }}
            </el-button>

          </el-form-item>
        </div>
        <el-form-item label="券：" prop="ranking" class="is-required">
          <div>
            <!--            <el-select v-model="form.type" placeholder="请选择">-->
            <!--              <el-option :value="0" label="手工上架商品"/>-->
            <!--              <el-option :value="1" label="自动从类别中获取"/>-->
            <!--            </el-select>-->
            <!--            <el-button v-if="form.type==1" icon="el-icon-plus" size="small" round type="text" @click="addCategory">-->
            <!--              选择类目-->
            <!--            </el-button>-->
            <el-button icon="el-icon-plus" size="small" round type="text" @click="addCoupon">增加券</el-button>
          </div>

          <el-form-item prop="couponList" class="is-required">
            <el-table
              :data="form.couponList"
              style="width: 100%"
              empty-text="未选择券"
              border
              stripe
              class="coupon-container"
              size="small"
              max-height="500"
            >
              <el-table-column prop="couponId" label="批次号" />
              <el-table-column prop="couponName" label="名称" />
              <el-table-column prop="couponType" label="类型">
                <template slot-scope="scope">
                  {{ $store.getters.cardCouponTypeKeyOptions[scope.row.couponType]||"--" }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    round
                    type="text"
                    class="app-text-color-danger"
                    @click="delCoupon(scope.$index)"
                  >删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :disabled="loading" size="small" round @click="hide">取 消</el-button>
        <el-button :disabled="loading" size="small" round type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 组件 -->
    <!--券2.0 筛选表格 -->
    <DialogCardCouponTable
      ref="dialogCardCouponTable"
      :card-coupon-type="['cash','discount','exchange','cash_wx_pay','cash_wx_busi','discount_wx_busi']"
      :has-checked-ids="hasCheckedCardCouponIds"
    />
  </div>
</template>

<script>
import DialogCardCouponTable from '@/components/DialogCardCouponTable'
import { mapGetters } from 'vuex'
import { imgUploadUrl } from '@/api/upload'
import wxaBuildConfig from '@/views/wxaBuildModule/config'

export default {
  components: {
    DialogCardCouponTable
  },
  data() {
    return {
      // 校验字段
      rules: {
        title: [
          {
            required: true,
            trigger: ['blur', 'change'],
            message: '请输入标题'
          }
        ],
        // pic: [
        //   {
        //     required: false,
        //     message: '请上传图片',
        //     trigger: ['blur', 'change']
        //   }
        // ],
        couponList: [
          {
            type: 'array',
            required: true,
            message: '请选择',
            trigger: ['blur', 'change']
          }
        ]
      },
      // 配置
      resolve: null,
      reject: null,
      imageUploadUrl: imgUploadUrl,
      moduleNameOptions: null,
      // 状态
      dialogVisible: null,
      loading: false,
      // 数据
      classifyCode: 'DEFAULT',
      mode: 'add',
      hasCheckedCardCouponIds: [],
      form: {
        titleType: 'text', // no-params
        subTitle: null, // no-params
        pic: null, // no-params
        description: null,
        couponList: [],
        title: null // no-params
      }
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl', 'activePageForm'])
  },
  watch: {
    'form.type'() {
      this.$nextTick((res) => {
        this.$refs.form.clearValidate(['couponList'])
      })
    }
  },
  methods: {
    /**
     * 弹框相关
     */
    open({ mode = 'add', row = null }) {
      this.moduleNameOptions = wxaBuildConfig[this.classifyCode].moduleName
      this.mode = mode
      if (mode === 'edit') {
        if (row.bg) {
          row.titleType = 'image'
        } else {
          row.titleType = 'text'
        }
        if (!row.couponList) row.couponList = []
        this.form = JSON.parse(JSON.stringify(row))
      }
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    close() {
      this.loading = false
      this.form = {
        titleType: 'text', // no-params
        subTitle: null, // no-params
        pic: null, // no-params
        description: null,
        couponList: [],
        title: null // no-params
      }
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    /**
     * 数据组
     */

    /**
     * 按钮组
     */
    // 确 定
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true
          const params = JSON.parse(JSON.stringify(this.form))
          if (params.titleType === 'text') {
            params.bg = ''
          } else {
            params.title = ''
            params.subTitle = ''
          }
          this.hasCheckedCardCouponIds = []
          params.couponList.forEach(v => {
            this.hasCheckedCardCouponIds.push(v.couponId)
          })
          params.couponIds = this.hasCheckedCardCouponIds
          this.resolve && this.resolve(params)
          this.hide()
        }
      })
    },

    // 删除类目
    delCategory(index) {
      this.form.categoryList.splice(index, 1)
    },

    // 新增商品
    addCoupon() {
      this.hasCheckedCardCouponIds = []
      this.form.couponList.forEach(v => {
        this.hasCheckedCardCouponIds.push(v.couponId)
      })
      this.$nextTick(() => {
        this.$refs.dialogCardCouponTable.open().then(res => {
          this.$refs.form.clearValidate(['couponList'])
          this.form.couponList = this.form.couponList.concat(res)
        })
      })
    },

    // 删除商品
    delCoupon(index) {
      this.form.couponList.splice(index, 1)
    },

    // 上传图标之前
    handleImgBefore(file) {
      return this.beforeUploadImg(file, this, 0, 0, 1, ['JPG', 'PNG', 'GIF'])
    },

    // 上传图标成功
    handleImgSuccess(res, file, type) {
      if (res.code === 0) {
        this.form[type] = res.data.path
        this.$refs.form.clearValidate([type])
      } else {
        this.$message.error(res.msg)
      }
    }

    /**
     * 状态组
     */

    /**
     * 方法组
     */
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.w-200 {
  width: 200px;
}

.w-400 {
  width: 400px;
}

/* 列表 */
.category-container {
  margin-top: 10px;

  .cell-item {
    display: flex;
  }
}

.coupon-container {
  margin-top: 10px;

  .cover-img {
    width: 40px;
    height: 40px;
  }
}

/* 上传图片 */
.upload-container {
  display: flex;

  .el-icon-plus {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 36px;
    color: #8c939d;
  }

  .img {
    display: block;
  }
}
</style>
